package cn.jbit.easybuy.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.jbit.easybuy.dao.ProductCategoryDao;
import cn.jbit.easybuy.dao.impl.ProductCategoryDaoImpl;
import cn.jbit.easybuy.entity.Page;
import cn.jbit.easybuy.entity.Product;
import cn.jbit.easybuy.entity.ProductCategory;
import cn.jbit.easybuy.service.ProductCategoryService;
import cn.jbit.easybuy.service.ProductService;
import cn.jbit.easybuy.service.impl.ProductCategoryServiceImpl;
import cn.jbit.easybuy.service.impl.ProductServiceImpl;

@WebServlet(urlPatterns = {"/home"},name = "Home")
public class HomeServlet extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ProductCategoryService pcService = new ProductCategoryServiceImpl();
		ProductService pService = new ProductServiceImpl();
		//左侧分类
		List<ProductCategory> pcList = pcService.findAll();
		
		String opr = request.getParameter("opr");
		if (opr == null) {
			opr = "list";
		}
		String pageNo = request.getParameter("pageNo");
		if (pageNo == null) {
			pageNo = "1";
		}
		int pageSize = 8;
		Page page = null;
		if (opr.equals("list")) {
			page = pService.findAll(Integer.valueOf(pageNo), pageSize);
		} else if (opr.equals("product_list")){
			String categoryId = request.getParameter("categoryId");
			page = pService.findByCategory(Integer.valueOf(pageNo), pageSize, Long.valueOf(categoryId));
		}
		
		
		request.setAttribute("page", page);
		request.getSession().setAttribute("pcList", pcList);
		request.getRequestDispatcher("index.jsp").forward(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
